package com.beiding.workordersystem.common.service;

import com.beiding.workordersystem.common.helper.EntityHelper;
import com.beiding.workordersystem.common.helper.IdCreator;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Date;
import java.util.Map;

public class BaseService {

    @Autowired
    private IdCreator idCreator;

    @Autowired
    private EntityHelper entityUtils;

    protected String createId() {
        return idCreator.create();
    }

    protected Date current() {
        return new Date();
    }

    protected boolean fillId(Object o) {
        return entityUtils.fillId(o);
    }

    protected boolean fillId(Object o, String idName) {
        return entityUtils.fillId(o, idName);
    }

    protected boolean isEmpty(Object o) {
        if (o instanceof String) {
            return "".equals(o);
        } else if (o instanceof Collection) {
            return ((Collection) o).size() == 0;
        } else if (o instanceof Map) {
            return ((Map) o).size() == 0;
        } else if (o instanceof Object[]) {
            return ((Object[]) o).length == 0;
        }
        return o == null;
    }

    protected boolean notEmpty(Object o) {
        return !isEmpty(o);
    }

    protected void init(Object o) {
        Field[] declaredFields = o.getClass().getDeclaredFields();
        for (Field declaredField : declaredFields) {
            declaredField.setAccessible(true);
            if (declaredField.getType() == Boolean.class) {
                try {
                    if (declaredField.get(o) == null) {
                        declaredField.set(o, false);
                    }
                } catch (IllegalAccessException ignore) {
                }
            }
        }
    }

}
